package com.hmkj.web.controller.pay;

import com.hmkj.core.api.umf.domain.ResultCode;
import com.hmkj.core.api.umf.domain.UmfCommon;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.po.amount.Recharge;
import com.hmkj.core.service.amount.CashService;
import com.hmkj.core.service.amount.RechargeService;
import com.hmkj.web.controller.GenericController;
import com.umpay.api.exception.VerifyException;
import com.umpay.api.paygate.v40.Plat2Mer_v40;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Created by 陌上人 on 2077/7/7 16:20.
 * 联动优势支付接口
 */
@Api(description = "联动优势支付接口相关")
@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL + "/pay")
public class UmpayNotifyController extends GenericController<Integer, Recharge> {

    @Autowired
    RechargeService rechargeService;
    @Autowired
    CashService cashService;

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "联动优势h5收银台异步回调接口", notes = "联动优势h5收银台异步回调接口")
    @ResponseBody
    @RequestMapping(value = "payResultNotify", method = RequestMethod.GET)
    public Map payResultNotify(@ApiParam("请求对象") HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        //构建响应参数
        Map<String, String> reqData = new HashMap<>(16);
        Map<String, String> resData = new HashMap<>(16);
        try {
            Map<String, String> ht = new HashMap<>(25);
            for (String key : parameterMap.keySet()) {
                String[] val = parameterMap.get(key);
                ht.put(key, (val == null || val.length < 1) ? "" : val[0]);
            }
            String signMsg;
            try {
                reqData = Plat2Mer_v40.getPlatNotifyData(ht);
                resData.put("ret_code", "0000");
                signMsg = "平台通知数据验签成功";
            } catch (VerifyException e) {
                System.out.println("验证签名发生异常" + e);
                resData.put("ret_code", "1111");
                signMsg = ("验证签名发生异常: " + e);
            }
            if (ResultCode.RESULT_CODE_OK.equals(resData.get(UmfCommon.RET_CODE))) {
                //U付交易号
                String tradeNo = reqData.get("trade_no");
                //商户订单号
                String orderId = reqData.get("order_id");
                //付款金额
                String amount = reqData.get("amount");
                //交易状态
                String tradeState = reqData.get("trade_state");
                //银行流水
                String paySeq = reqData.get("pay_seq");
                //支付协议号
                String usrPayAgreementId = reqData.get("usr_pay_agreement_id");
                //交易错误码
                String errorCode = reqData.get("error_code");
                //支付银行
                String gateId = reqData.get("gate_id");
                //银行卡卡号后四位
                String lastFourCardId = reqData.get("last_four_cardid");
                if (tradeState.equals(ResultCode.TradeStateEnum.TRADE_SUCCESS.getCode())) {
                    //进行业务处理 成功处理用户资金
                    rechargeService.handleRechargeByUmpay(tradeNo, orderId, amount, tradeState,errorCode, paySeq, usrPayAgreementId, gateId, lastFourCardId);
                }
                resData.put("order_id", orderId);
                resData.put("order_id", reqData.get("mer_date"));
                signMsg = "success";
            }
            resData.put("mer_id", reqData.get("mer_id"));
            resData.put("sign_type", reqData.get("sign_type"));
            resData.put("version", reqData.get("version"));
            resData.put("ret_msg", signMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resData;
    }

    @ApiOperation(value = "联动优势付款异步回调接口", notes = "联动优势付款异步回调接口")
    @ResponseBody
    @RequestMapping(value = "fuKuanResultNotify", method = RequestMethod.POST)
    public Map fuKuanResultNotify(@ApiParam("请求对象") @RequestParam HttpServletRequest request) {
        //构建响应参数
        Map<String, String> reqData = new HashMap<>(16);
        Map<String, String> resData = new HashMap<>(16);
        try {
            String html = request.getParameter("html");
            String htmlPar = html.substring(html.lastIndexOf("?") + 1);
            String[] strArray = htmlPar.split("&");
            Map<String, String> ht = new HashMap<>(25);
            for (String aStrArray : strArray) {
                ht.put(aStrArray.substring(0, aStrArray.indexOf("=")), URLDecoder.decode(aStrArray.substring(aStrArray.lastIndexOf("=") + 1), "UTF-8"));
            }
            String signMsg;
            try {
                reqData = Plat2Mer_v40.getPlatNotifyData(ht);
                resData.put("ret_code", "0000");
                signMsg = "平台通知数据验签成功";
            } catch (VerifyException e) {
                System.out.println("验证签名发生异常" + e);
                resData.put("ret_code", "1111");
                signMsg = ("验证签名发生异常: " + e);
            }
            log.info(signMsg);
            if (ResultCode.RESULT_CODE_OK.equals(resData.get(UmfCommon.RET_CODE))) {
                //商户订单号
                String orderId = reqData.get("order_id");
                //U付交易号
                String tradeNo = reqData.get("trade_no");
                //付款金额
                String amount = reqData.get("amount");
                //交易状态
                String tradeState = reqData.get("trade_state");
                //返回信息
                String retMsg = reqData.get("ret_msg");
                //处理回调处理
                cashService.handleCashByUmpay(tradeNo,orderId,amount,tradeState,retMsg);

                resData.put("mer_id", reqData.get("mer_id").toString());
                resData.put("sign_type", reqData.get("sign_type").toString());
                resData.put("version", reqData.get("version").toString());
                resData.put("ret_msg", "success");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resData;
    }

}

